package com.cyx;

import java.util.Arrays;

/**
 * @author 陈裕星
 * @version 1.0
 */
public class 寻找两个数组的中位数 {
    public static void main(String[] args) {
        int[] nums1 = {2};
        int[] nums2 = {1};
        int[] res = new int[nums1.length + nums2.length];
        merge(res,nums1,nums2);
        double mid = 0;
        //找出中位数
        if(res.length % 2 == 0){
            //偶数个
            mid = (res[res.length / 2-1] + res[res.length / 2])/2.0;
        }else{
            mid = res[res.length/2] * 1.0;
        }
        System.out.println(Arrays.toString(res));
        System.out.println(mid);
    }
    //合并两个有序数组
    static void merge(int[] res,int[] nums1,int[] nums2){
        int i = 0,j = 0,k = 0;
        while(i < nums1.length && j < nums2.length){
            if(nums1[i] >= nums2[j]){
                res[k] = nums2[j];
                j++;
            }else {
                res[k] = nums1[i];
                i++;
            }
            k++;
        }
        while(i < nums1.length){
            res[k] = nums1[i];
            i++;
            k++;
        }
        while(j < nums2.length){
            res[k] = nums2[j];
            j++;
            k++;
        }
    }
}
